import sys
import time

import requests
import json
import os
from feed_back import CreateExcel

def make_url_info():
    url = r'https://content.bytedance.net/user/feedback/ajax/search/get_feedback_list/?' \
          r'product_type=1&' \
          r'search_type=label&' \
          r'start_time=2019-01-07%2012:00:00&' \
          r'end_time=2019-01-08%2000:00:00&' \
          r'label1_ids=9336&' \
          r'label2_ids=9341,9940,9342'

    headers = {
        'Accept': 'application/json, text/plain, */* ',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Connection': 'keep-alive',
        'Cookie': 'sessionid=8mwzhmg8duzpxi0zjze4srkiee2ovtjh; '
                  '_ga=GA1.2.110216724.1546830018; '
                  '_gid=GA1.2.2113249651.1546830018',
        'Host': 'content.bytedance.net',
        'Referer': url,
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) '
                      'AppleWebKit/537.36 (KHTML, like Gecko) '
                      'Chrome/69.0.3497.100 Safari/537.36'
    }
    return url, headers


def show_url(url, headers):
    print(url)
    r = requests.get(url, headers=headers)
    print(r.json())


def get_feedback_info(url, headers, index):
    r = requests.get(url, headers=headers)
    try:
        responser = r.json()
    except json.decoder.JSONDecodeError:
        print('json解析失败，错误url: {}'.format(url))
        return None

    try:
        fb_info = responser['rows'][index]
    except KeyError:
        print('查看不到信息， url: {0}, 参考信息信息: {1}'.format(url, responser['message']))
        return None
    except Exception as e:
        print('出现其他异常，错误原因: {}', e)
        return None

    else:
        return fb_info


def create_fbinfo_dict(fb_info, url):
    fb_handle_dict = {}

    if fb_info is None:
        return

    fb_key = ['create_time', 'id', 'app_id', 'device_id', 'content', 'label3', 'network_type',
              'platform', 'channel']
    if fb_info['create_time'] > '2019-01-01 00:00:00':
        print('用户反馈地址', url)
        for key in fb_key:
            fb_handle_dict[key] = fb_info[key]
        fb_handle_dict['url'] = 'https://content.bytedance.net/user/feedback/list/?id=' + str(fb_info['id'])

    print()

    return fb_handle_dict


def main():
    index = 0
    excel = CreateExcel()
    while 1:
        url, header = make_url_info()
        fb_handle = get_feedback_info(url, header, index)
        fb_dict = create_fbinfo_dict(fb_handle, url)
        if fb_dict is None:
            break
        excel.insert_feed_back(**fb_dict)
        index += 1
        time.sleep(1)


if __name__ == '__main__':
    main()
